package com.qd.pay.util;

import com.cdqidi.exception.ApiException;
import com.jfinal.kit.Base64Kit;
import com.jfinal.kit.HashKit;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AesUtil {
    private AesUtil() {

    }

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";

    /**
     * AES加密
     *
     * @param data   加密字符串
     * @param apiKey 秘钥
     * @return 加密后的字符串
     * @throws ApiException 异常
     */
    public static String encryptData(String data, String apiKey) {
        try {
            SecretKeySpec key = new SecretKeySpec(HashKit.md5(apiKey).toLowerCase().getBytes(), ALGORITHM);
            // 创建密码器
            Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return Base64Kit.encode(cipher.doFinal(data.getBytes()));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException |
                 InvalidKeyException e) {
            throw new ApiException(e);
        }
    }

    /**
     * AES加密
     *
     * @param base64Data 经过base64编码以后的字符串
     * @param apiKey     秘钥
     * @return 解密后的字符串
     * @throws ApiException 异常
     */
    public static String decryptData(String base64Data, String apiKey) {

        try {
            SecretKeySpec key = new SecretKeySpec(HashKit.md5(apiKey).toLowerCase().getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(Base64Kit.decode(base64Data)));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException |
                 InvalidKeyException e) {
            throw new ApiException(e);
        }

    }
}
